
# 定义菜品接口名称
# banner图的加载 和 中间部分的类别用同一个接口进行返回     内容（搜索接口返回）
from web.controllers.api import route_api
from flask import request,jsonify,g
from common.libs.UrlManager import UrlManager
from common.models.food.FoodCat import FoodCat
# banner图会选择比较火的餐品进行展示
from common.models.food.Food import Food
from sqlalchemy import or_
from common.models.member.MemberCart import MemberCart

# 写网络请求，再获取后台数据
# 注册界面的url地址
# 第一个url：food_index ：返回 banner图和我们首页的分类信息  data字典类型
@route_api.route("/food/index")
def foodIndex():
    resp ={'code':200,'msg':'操作成功','data':{}}
    # 取出可展示的类别(展示分类列表)
    cat_list = FoodCat.query.filter_by(status=1).order_by(FoodCat.weight.desc()).all()
    # 将数据进行统一构造
    data_cat_list =[]#构造的数组
    # 返回字段有id
    data_cat_list.append({
        'id':0,
        'name':'全部'
    })
    # 如果在数据库中能够查询出我们的类别字段，则进行循环展示
    if cat_list:
        for item in cat_list:
            tmp_data = {
                "id":item.id,
                "name":item.name
            }
            data_cat_list.append(tmp_data)
    resp['data']['cat_list'] = data_cat_list

    # 类别等于1表示商品是没有被删除的
    # 将数据库中取出的数据 按照总销量的大小倒序排列，b并且根据餐品的id倒序排，取出三个数据展示
    food_list=Food.query.filter_by(status =1)\
        .order_by(Food.total_count.desc(),Food.id.desc()).limit(3).all()

    # 将food_list格式化再展示给前端
    data_food_list = []
    if food_list:
        for item in food_list:
            tmp_data = {
                "id":item.id,
                "pic_url":UrlManager.buildImageUrl(item.main_image)
            }
            data_food_list.append(tmp_data)
    resp['data']['banner_list']= data_food_list
    return jsonify(resp)

# 第二个接口：搜索接口：用来返回我们的搜索信息
@route_api.route("/food/search")
def foodSearch():
    # 第一步设置返回值   第二部 最终返回json ，所有数据放入data区域里来   ，第三部取得请求参数
    resp ={'code':200,'msg':'操作成功','data':{}}
    req = request.values
    cat_id =int(req['cat_id']) if 'cat_id' in req else 0
    mix_kw = str(req['mix_kw']) if 'mix_kw' in req else ''
    p = int(req['p']) if 'p' in req else 1
    if p<1:
        p=1
    query = Food.query.filter_by(status=1)
    page_size=10
    # 当前页数
    offset =(p-1)*page_size

    # 通过分类id查询分类
    if cat_id> 0:
        query = query.filter(Food.cat_id == cat_id)

    if mix_kw:
        # 查询名称和描述
        rule = or_(Food.name.ilike("%{0}%".format(mix_kw)), Food.tags.ilike("%{0}%".format(mix_kw)))
        query = query.filter(rule)

    # total_count:卖出的总数量
    food_list = query.order_by(Food.total_count.desc(),Food.id.desc())\
        .offset(offset).limit(page_size).all()
    # 将list转换成前端所需要的结构 || min_price:最低价格，打折专用
    data_food_list =[]
    if food_list:
        for item in food_list:
            tmp_data ={
                'id':item.id,
                'name':item.name,
                'price':str(item.price),
                'min_price':str(item.price),
                'pic_url':UrlManager.buildImageUrl(item.main_image)
            }
            data_food_list.append(tmp_data)

    resp['data']['list'] = data_food_list
    resp['data']['has_more'] = 0 if len(data_food_list) < page_size else 1
    return jsonify(resp)

@route_api.route("/food/info",methods=["POST","GET"])
def foodInfo():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    id =int(req['id']) if 'id' in req else 0
    food_info =Food.query.filter_by(id =id ).first()
    if not food_info or not food_info.status:
        resp['code'] =-1
        resp['msg'] ="美食不存在"
        return jsonify(resp)

    # 想要取得购物车信息的话，也要取得会员信息的
    member_info=g.member_info
    cart_number =0
    if member_info:
        cart_number = MemberCart.query.filter_by(member_id = member_info.id).count()

    resp['data']['info']={
        "id":food_info.id,
        "name":food_info.name,
        "summary":food_info.summary,
        "total_count":food_info.total_count,
        "comment_count":food_info.comment_count,
        "main_image":UrlManager.buildImageUrl(food_info.main_image),
        "price":str(food_info.price),
        "stock":food_info.stock,
        "pics":[UrlManager.buildImageUrl(food_info.main_image)]
    }
    # 显示购物车中有几个商品
    # 将cart_number统一放到前台去
    resp['data']['cart_number'] =cart_number
    return jsonify(resp)